#提取所有出现过的IPv6地址，提取为AtoB的格式
import os
import codecs
import re
folder ='./result/trace/' #存储文本的目录
#下一行为IPv6匹配的正则表达式
ipv6_addr='([a-f0-9]{1,4}(:[a-f0-9]{1,4}){7}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){0,7}::[a-f0-9]{0,4}(:[a-f0-9]{1,4}){0,7})'

#获取目录下所有文件
def file_name(file_dir):   
    for root, dirs, files in os.walk(file_dir):  
        return files

file_names = file_name(folder)
f = open('./result/ip6_addr_s2d.txt','w')

for filename in file_names:
    count = 0
    text = codecs.open(folder+filename,'r','gb2312').read()
    #f.write(filename+'\n')
    addr_all = re.findall(ipv6_addr,text)
    for addr in addr_all:
        if count == 0:
            temp_addr_des = addr[0]
            count += 1
        elif count == 1:
            temp_addr_up = addr[0]
            count += 1
        else:
            if addr[0] != temp_addr_up:
                f.write(temp_addr_up+','+addr[0]+'\n')
                temp_addr_up = addr[0]
    print(addr[0],temp_addr_des)
    if addr[0] != temp_addr_des:
        f.write(addr[0]+','+temp_addr_des+'\n')
    #f.write('\n')

f.close()
print('finish')